﻿$(function () {
    //setup the tabs
    $("#SettingsTabs").tabs();

    //setup sortable states
    $("#SortableStates").sortable({
        handle: ".SortableHandle",
        stop: OnSortingDone
    });

    //make the states look nice on hover
    $(".SortableHandle").hover(
        function () {
            $(this).addClass("ui-state-hover");
        },
        function () {
            $(this).removeClass("ui-state-hover");
        }
    );

    //make the trash btn functional
    $(".TrashBtn").button({
        text: false,
        icons: { primary: "ui-icon-trash" }
    });

    //catch the 'enter' keydown for the 'add new state' control
    //do an async POST to a WebMethod to add to the database
    $("#NewStateControl").keydown(function (e) {
        if (e.keyCode == 13) {
            OnNewStateEnterKey();
            
            //keep weird behavior from occuring
            e.preventDefault();
        }
    });

    //catch the 'enter' keydown for the 'add new state' control
    //do an async POST to a WebMethod to add to the database
    $("#NewPositionControl").keydown(function (e) {
        if (e.keyCode == 13) {
            OnNewPositionEnterKey();

            //keep weird behavior from occuring
            e.preventDefault();
        }
    });

    
    //catch the 'enter' keydown for the 'add new state' control
    //do an async POST to a WebMethod to add to the database
    $("#NewHeardAboutControl").keydown(function (e) {
        if (e.keyCode == 13) {
            OnNewHeardAboutEnterKey();

            //keep weird behavior from occuring
            e.preventDefault();
        }
    });

});

function OnNewHeardAboutEnterKey() {
    var newName = $("#NewHeardAboutControl").val();

    if (newName.length > 0) {
        $("#NewHeardAboutControl").val("").blur(); //unfocus the control
        PageMethods.AddHeardAbout(newName,
            function (newId) {
                OnNewItemAdded(newId, newName, $("#SettingsHeardAboutsEmpties"), 
                    "HeardAbout", DeleteHeardAbout, $("#SettingsHeardAbouts"));
            },
            function () { }
        );
    }
}

function OnNewStateEnterKey() {
    var newName = $("#NewStateControl").val();

    if (newName.length > 0) {
        $("#NewStateControl").val("").blur(); //unfocus the control
        PageMethods.AddState(newName,
            function (newId) {
                OnNewItemAdded(newId, newName, $("#SortableStatesEmpties"),
                    "State", DeleteState, $("#SortableStates"));
            },
            function () { }
        );
    }
}

function OnNewPositionEnterKey() {
    var newName = $("#NewPositionControl").val();

    if (newName.length > 0) {
        $("#NewPositionControl").val("").blur(); //unfocus the control
        PageMethods.AddPosition(newName,
            function (newId) {
                OnNewItemAdded(newId, newName, $("#SettingsPositionsEmpties"),
                    "Position", DeletePosition, $("#SettingsPositions"));
            },
            function () { }
        );
    }
}



//when sorting is done, clear the state orders and then
//set them to their new values
function OnSortingDone() {
    var indexes = [];

    $("#SortableStates").children().each(function (i) {
        indexes[i] = $(this).find(".HiddenID").val();
    });

    //alert(indexes);

    PageMethods.SetOrderIndex(indexes,
        function () { /*TODO: show success?*/ },
        function () { /*TODO: show errors?*/ }
    );
}



function OnNewItemAdded(newId, newName, emptiesElement, type, deleteFn, container) {
    if (emptiesElement.children().length > 0) {
        // get the first empty and use it
        var emptyItem = emptiesElement.children().first();

        emptyItem.attr("id", "Settings" + type + newId); //set the id
        emptyItem.find("input").val(newName); //set the value
        emptyItem.find(".HiddenID").val(newId); //set the id
        emptyItem.find("button").unbind("click"); //remove current function
        emptyItem.find("button").click(function () { deleteFn(newId); });   //set the delete function
        emptyItem.appendTo(container);

    } else {
        //call page refresh, out of empties to use
        location.reload();
    }

}




//function called when user clicks the trash btn on a state
function DeleteState(id) {
    PageMethods.DeleteState(id,
        function (data) { DeleteItemCallback(data, id, "State", $("#SortableStatesEmpties")); },
        function () {
            //todo, show error
        }
    );

    return false;
}

function DeletePosition(id) {
    PageMethods.DeletePosition(id,
        function (data) { DeleteItemCallback(data, id, "Position", $("#SettingsPositionsEmpties")); },
        function () {
            //todo, show error
        }
    );

    return false;
}

function DeleteHeardAbout(id) {
    PageMethods.DeleteHeardAbout(id,
        function (data) { DeleteItemCallback(data, id, "HeardAbout", $("#SettingsHeardAboutsEmpties")); },
        function () {
            //todo, show error
        }
    );

    return false;
}

//function called when DeleteState has returned successfully from server
function DeleteItemCallback(returnVal, id, type, emptiesElement) {
    //take the slot that was deleted, clear it, and hide it
    //(adds to the bank of empty slots that can be used when adding a state)
    if (returnVal) {
        var accessor = $("#Settings" + type + id);
        accessor.attr("id", "Settings" + type);
        accessor.find("input").val(""); //clear the value
        accessor.find(".HiddenID").val(""); //clear the id
        accessor.find("button").unbind("click"); //remove current function
        accessor.appendTo(emptiesElement);
    } else {
        //TODO: show pretty error message
        alert('Applications or Candidates are still associatied with this item');
    }
}





